package net.oschina.archx.rmi.processor;

import net.oschina.archx.rmi.annotation.RemoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.remoting.rmi.RmiServiceExporter;
import org.springframework.stereotype.Component;

import java.rmi.RemoteException;

/**
 * RemoteAnnotationBeanPostProcessor
 *
 * @author Archx[archx@foxmail.com]
 * @date 2016/2/24 0024
 */
@Component
public class RemoteAnnotationBeanPostProcessor implements BeanPostProcessor, BeanFactoryPostProcessor {

    protected ConfigurableListableBeanFactory beanFactory;

    final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        logger.info("名称: {}", beanName);
        // RemoteService
        if (clazz.isAnnotationPresent(RemoteService.class)) {
            RemoteService rs = clazz.getAnnotation(RemoteService.class);
            RmiServiceExporter rse = new RmiServiceExporter();
            String serviceName = rs.serviceName();
            Class<?> serviceInterface = rs.serviceInterface();
            int registryPort = rs.registryPort();
            rse.setServiceName(serviceName);
            rse.setServiceInterface(serviceInterface);
            rse.setRegistryPort(registryPort);
            rse.setService(bean);
            //rse.setRegistryHost("192.168.1.102");

            logger.info("注册服务: {} 接口: {} 端口: {}", serviceName, serviceInterface.getName(), registryPort);

            try {
                rse.afterPropertiesSet();
                return rse;
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        return bean;
    }
}
